<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">楼宇名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" @clear="doSearch" />
      <el-button type="primary" @click="doSearch">查询</el-button>
      <el-button type="primary" @click="exportExcel">导出Excel</el-button>
    </div>

    <!-- 添加楼宇弹框 -->
    <el-dialog
      :title="dialogTitle"
      :visible="dialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <!-- 表单接口 -->
      <div class="form-container">
        <el-form ref="addForm" :model="addForm" :rules="addFormRules">
          <el-form-item label="楼宇名称" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="楼宇层数" prop="floors">
            <el-input v-model="addForm.floors" />
          </el-form-item>
          <el-form-item label="在管面积" prop="area">
            <el-input v-model="addForm.area" />
          </el-form-item>
          <el-form-item label="物业费" prop="propertyFeePrice">
            <el-input v-model="addForm.propertyFeePrice" />
          </el-form-item>
        </el-form>
      </div>

      <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>

      <template #footer>
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>

    <el-button type="primary" @click="addBuilding">添加楼宇</el-button>

    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="buildingList"
      >
        <el-table-column
          type="index"
          label="序号"
        />
        <el-table-column
          label="楼宇名称"
          width="180"
          prop="name"
        />
        <el-table-column
          label="层数"
          prop="floors"
        />
        <el-table-column
          label="在管面积(m²)"
          width="120"
          prop="area"
        />
        <el-table-column
          label="物业费(元/m²)"
          width="120"
          prop="propertyFeePrice"
        />
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            {{ formatStatus(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="mini" type="text" @click="edit(scope.row)">编辑</el-button>
            <el-button size="mini" type="text" @click="confirmDel(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="50"
        @current-change="pageChange"
      />
    </div>
  </div>
</template>

<script>
import { getBuildingListAPI, createBuildingListAPI, delBuildingListAPI, editBuildingListAPI } from '@/api/building'
import * as XLSX from 'xlsx'
export default {
  name: 'Building',
  data() {
    return {
      buildingList: [], // table列表
      params: { // 请求参数
        page: 1,
        pageSize: 10,
        name: '' // 搜索条件
      },

      addForm: {
        name: '',
        floors: null,
        area: null,
        propertyFeePrice: null
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入楼宇名称', trigger: 'blur' }
        ],
        floors: [
          { required: true, message: '请输入楼宇层数', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '请输入楼宇面积', trigger: 'blur' }
        ],
        propertyFeePrice: [
          { required: true, message: '请输入楼宇物业费', trigger: 'blur' }
        ]
      },
      total: 0,
      dialogVisible: false // 控制弹框显示
    }
  },
   computed: {
      dialogTitle() {
        return this.addForm.id ? '编辑楼宇' : '添加楼宇'
      }
    },
  mounted() {
    this.getBuildingList()
  },

  methods: {
    async getBuildingList() {
      const res = await getBuildingListAPI(this.params)
      this.buildingList = res.data.rows
      this.total = res.data.total
    },
    // 分页切换
    pageChange(page) {
      this.params.page = page
      this.getBuildingList()
    },
    // 搜索
    doSearch() {
      this.params.page = 1
      this.getBuildingList()
    },
    formatStatus(status) {
      const statusMap = {
        0: '租赁中',
        1: '闲置中'
      }
      return statusMap[status]
    },
   // 删除
async confirmDel(id) {
  this.$confirm('确认删除当前楼宇吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await delBuildingListAPI(id)
    this.getBuildingList()
    // 添加删除成功提示
    this.$message({
      type: 'success',
      message: '删除成功'
    })
  }).catch(() => {
    // 用户点击取消时的处理（可选）
    this.$message({
      type: 'info',
      message: '已取消删除'
    })
  })
},
// 点击编辑时打开弹框并回显数据
async edit(row) {
  // 1. 打开弹框
  this.dialogVisible = true

  // 2. 解构必要字段
  const { id, area, floors, name, propertyFeePrice } = row

  // 3. 设置表单数据
  this.addForm = {
    id,
    area,
    floors,
    name,
    propertyFeePrice
  }
},

// 关闭弹窗并清空表单
closeDialog() {
  this.dialogVisible = false
  this.addForm = {
    name: '',
    floors: null,
    area: null,
    propertyFeePrice: null,
    id: null
  }
},
// 导出Excel
exportExcel() {
  // 1. 复制数据，避免修改原始数据
  const exportData = this.buildingList.map(item => ({
    '楼宇名称': item.name,
    '层数': item.floors,
    '在管面积(m²)': item.area,
    '物业费(元/m²)': item.propertyFeePrice,
    '状态': this.formatStatus(item.status)
  }));

  // 2. 创建工作表
  const ws = XLSX.utils.json_to_sheet(exportData);

  // 3. 创建工作簿并添加工作表
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '楼宇列表');

  // 4. 导出文件
  XLSX.writeFile(wb, '楼宇列表.xlsx');
},
// 打开添加楼宇弹窗
addBuilding() {
  this.dialogVisible = true
},

// 新增/编辑统一提交方法
confirmAdd() {
  this.$refs.addForm.validate(async valid => {
    if (valid) {
      try {
        // 根据是否有 id 区分新增或编辑
        if (this.addForm.id) {
          await editBuildingListAPI(this.addForm)
          this.$message.success('编辑成功')
        } else {
          await createBuildingListAPI(this.addForm)
          this.$message.success('新增成功')
        }

        // 刷新列表 & 关闭弹窗
        this.getBuildingList()
        this.closeDialog()
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('操作失败，请稍后再试')
      }
    }
  })
}
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  padding: 4px 0px;
  text-align: right;
}

.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
</style>
